<script setup lang="ts">
import { useUserStore } from '@/store/modules/user';
import { to } from 'await-to-js';
import { LoadingInstance } from 'element-plus/es/components/loading/src/loading';
import { setToken } from '@/utils/auth';

const userStore = useUserStore();
const router = useRouter();
const route = useRoute();

let LoadingInstance: LoadingInstance;

const loginForm = ref({
  tenantId: '000000',
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: '',
  clientId: import.meta.env.VITE_APP_CLIENT_ID,
  grantType: 'password'
});

const redirect = ref('/');

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect && decodeURIComponent(newRoute.query.redirect);
  },
  { immediate: true }
);

const handleLogin = async () => {
  let err: Error | null;
  if (route.query.token) {
    // [err] = await to(userStore.loginByToken({ rq_token: route.query.token as string }));
    [err] = await to(userStore.login(loginForm.value));
    // setToken(route.query.token as string);
  } else {
    [err] = await to(userStore.login(loginForm.value));
  }
  if (!err) {
    const redirectUrl = redirect.value || '/';
    await router.push(redirectUrl);
  }
};

onMounted(async () => {
  try {
    LoadingInstance = ElLoading.service({ text: '正在加载数据...', background: 'rgba(9, 48, 111, 1)' });
    await handleLogin();
  } catch (error) {
    console.warn(error);
    await handleLogin();
  } finally {
    LoadingInstance.close();
  }
});
</script>
